/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.springboot.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.framework.util.JsonResultUtil;

/**
 * @description API全局异常处理
 * @date 2020年6月3日
 * @author dongbin
 * 
 */
@Component
public class ApiExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            if(request.getRequestURI().contains("/api/")) {
                //api拦截器已设置
                //response.setContentType("text/html;charset=UTF-8");
                
                if(ex!=null) {
                    response.getWriter().print(JsonResultUtil.getErrorJson(-1, ex.toString()));
                    response.getWriter().flush();
                    response.getWriter().close();
                }
            }
        }catch(Exception e) {
            
        }
        return null;
    }

}
